﻿using Elastic.Clients.Elasticsearch;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Cordyceps.Elastic.Tool.HealthChecks;

/// <summary>
/// </summary>
public class ElasticsearchHealthCheck : IHealthCheck
{
    private readonly ElasticsearchClient _client;
    private readonly IElasticsearchClientFactory _factory;

    /// <summary>
    /// Elasticsearch健康检查实现注入
    /// </summary>
    /// <param name="factory"></param>
    /// <param name="client"></param>
    public ElasticsearchHealthCheck(
        IElasticsearchClientFactory factory,
        ElasticsearchClient client)
    {
        _factory = factory;
        _client = client;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            // var isHealthy = await _factory.CheckClusterHealthAsync(_client);
            // return isHealthy 
            //     ? HealthCheckResult.Healthy("Elasticsearch集群状态正常") 
            //     : HealthCheckResult.Unhealthy("Elasticsearch集群状态异常");
            var result= HealthCheckResult.Healthy("Elasticsearch集群状态正常");
            return await Task.FromResult(result);
        }
        catch (Exception ex)
        {
            var result= HealthCheckResult.Unhealthy("Elasticsearch健康检查失败", ex);
            return await Task.FromResult(result);
        }
    }
}